package com.example.demo.service.impl; 

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.CacheRepositoryEntity;
import com.example.demo.mapper.ICacheRepositoryMapper;
import com.example.demo.service.IDataBaseCacheRepositoryService;

import lombok.extern.log4j.Log4j2;

/**
 * 
 * @author Administrator
 *
 */
@Log4j2
@Service("dataBaseCacheRepositoryService")
public class DataBaseCacheRepositoryServiceImpl extends ServiceImpl<ICacheRepositoryMapper,CacheRepositoryEntity> implements IDataBaseCacheRepositoryService {

	 int sessionTimeout = 6000000;
	
	 @Autowired
     public ICacheRepositoryMapper cacheRepositoryMapper;	 
	
	 public Object Get(String key) {		 
		 Map<String, Object> paramsMap=new HashMap<String, Object>();
		 paramsMap.put("objectKey", key);		 
		 return cacheRepositoryMapper.selectCache(paramsMap);
	 }
	 
	 public boolean Exists(String key) {
		 Map<String, Object> paramsMap=new HashMap<String, Object>();
		 paramsMap.put("objectKey", key);	
		 Integer result=cacheRepositoryMapper.getCacheCounts(paramsMap);
		 return result==0 ? false : true;
	 }
	 
	 public void Set(String key,Object value) {

		 Calendar calendar =Calendar.getInstance();  
	     calendar.setTime(new Date());
	     calendar.add(Calendar.MILLISECOND, (int)sessionTimeout);
	     Date expireTime=calendar.getTime();		 
		 
		 try {
			 
			 CacheRepositoryEntity entity = new CacheRepositoryEntity();
			 entity.setObjectKey(key);
			 entity.setObjectValue(value+"");
			 entity.setObjectDescription("");
			 entity.setExpireTime(expireTime);	
			 
			 if(!Exists(key)) {
				 cacheRepositoryMapper.addCache(entity); 
			 }			 
			 else {
				 cacheRepositoryMapper.updateCache(entity);
			 }			
			 
		 }
		 catch (Exception ex) {
			// TODO: handle exception
			log.info("写入数据库失败:"+ex.getMessage(),ex);
		 }
		 
	 }
	 
	 
	 public void Delete(String key) {		 
		 
		 Map<String, Object> paramsMap=new HashMap<String, Object>();
		 paramsMap.put("objectKey", key);
		 cacheRepositoryMapper.deleteCache(paramsMap);
		 
	 }
	 
	 public void Clear() {
		 
		 cacheRepositoryMapper.clearCache();
		 
	 }	
	 
}
